package com.hongxun.design.listeners;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;

import com.hongxun.design.MyApp;
import com.hongxun.design.interfaces.UpdateMap;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ToastShow;

import java.util.List;

/**
 * Created by zerdoor_pc on 2016/5/4.
 * 定位SDK监听函数
 */
public class MyLocationListenner implements BDLocationListener {
    MapView mMapView;
    BaiduMap mBaiduMap;
    boolean isFirstLoc = true; // 是否首次定位
    boolean iscountinue = false; // 是否持续定位
    boolean islocal = false; // 是否首次定位
    UpdateMap updateMap; // 定位相关
    BDLocation location;
    static LocationClient mLocClient;

    MyLocationListenner(MapView mMapView, UpdateMap updateMap) {
        this.mMapView = mMapView;
        flag=true;
        this.updateMap = updateMap;
        if (mMapView!=null) mBaiduMap = mMapView.getMap();

    }

    static MyLocationListenner inte;

    public static MyLocationListenner getint(MapView mMapView, UpdateMap updateMap) {
        if (inte == null) {
            inte = new MyLocationListenner(mMapView, updateMap);
            mLocClient = new LocationClient((Context) updateMap);
        }
        mLocClient.registerLocationListener(inte);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(2000);
        option.setIsNeedLocationPoiList(true);
        mLocClient.setLocOption(option);
        mLocClient.start();

        return inte;
    }

    public static MyLocationListenner getint( UpdateMap updateMap) {
        if (inte == null) {
            inte = new MyLocationListenner(null, updateMap);
            mLocClient = new LocationClient((Context) updateMap);
        }

        mLocClient.registerLocationListener(inte);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(2000);
        option.setIsNeedLocationPoiList(true);
        mLocClient.setLocOption(option);
        mLocClient.start();

        return inte;
    }

    public void setIsFirstLoc(boolean isFirstLoc) {
        this.isFirstLoc = isFirstLoc;
    }

    public void setCountinue(boolean iscountinue) {
        this.iscountinue = iscountinue;
    }

    public void setIsLocal(boolean islocal) {
        this.islocal = islocal;
    }

    public BDLocation getBDLocation() {
        return location;
    }
    boolean flag=true;
    @Override
    public void onReceiveLocation(BDLocation location) {
        // map view 销毁后不在处理新接收的位置
        if (location == null || mMapView == null) {
            return;
        }

        StringBuffer sb = new StringBuffer(256);
        sb.append("time : ");
        sb.append(location.getTime());
        sb.append("\nerror code : ");
        sb.append(location.getLocType());
        sb.append("\nlatitude : ");
        sb.append(location.getLatitude());
        sb.append("\nlontitude : ");
        sb.append(location.getLongitude());
        sb.append("\nradius : ");
        sb.append(location.getRadius());
        if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位结果
            sb.append("\nspeed : ");
            sb.append(location.getSpeed());// 单位：公里每小时
            sb.append("\nsatellite : ");
            sb.append(location.getSatelliteNumber());
            sb.append("\nheight : ");
            sb.append(location.getAltitude());// 单位：米
            sb.append("\ndirection : ");
            sb.append(location.getDirection());// 单位度
            sb.append("\naddr : ");
            sb.append(location.getAddrStr());
            sb.append("\ndescribe : ");
            sb.append("gps定位成功");
            success(location);
        } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 网络定位结果
            sb.append("\naddr : ");
            sb.append(location.getAddrStr());
            //运营商信息
            sb.append("\noperationers : ");
            sb.append(location.getOperators());
            sb.append("\ndescribe : ");
            sb.append("网络定位成功");
            success(location);
        } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
            sb.append("\ndescribe : ");
            sb.append("离线定位成功，离线定位结果也是有效的");
            success(location);
        } else if (location.getLocType() == BDLocation.TypeServerError) {
            sb.append("\ndescribe : ");
            sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            ToastShow.showShort(MyApp.activity, "获取定位信息失败,请检查网络与GPS是否正常工作！");

        } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
            sb.append("\ndescribe : ");
            sb.append("网络不同导致定位失败，请检查网络是否通畅");
            ToastShow.showShort(MyApp.activity, "获取定位信息失败,请检查网络与GPS是否正常工作！");

        } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
            sb.append("\ndescribe : ");
            sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            ToastShow.showShort(MyApp.activity, "获取定位信息失败,请检查手机是否正常工作,或重启手机！");

        }

        sb.append("\nlocationdescribe : ");
        sb.append(location.getLocationDescribe());// 位置语义化信息
        List<Poi> list = location.getPoiList();// POI数据
        if (list != null) {
            sb.append("\npoilist size = : ");
            sb.append(list.size());
            for (Poi p : list) {
                sb.append("\npoi= : ");
                sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
            }
        }
        MyLog.L(MString.SUCCESSED+ sb.toString());
        if (isFirstLoc) {
            close();
        }


    }


    public void success(BDLocation location){
        if (isFirstLoc) {
            if (location.getLongitude() == 4.9E-324||location.getLatitude() == 4.9E-324||location.getLongitude()<=0||location.getLatitude()<=0) {
                if (MyApp.activity != null&&flag){
                    flag=false;
                    ToastShow.showShort(MyApp.activity, "获取定位信息失败,请检查网络与GPS是否正常工作！");
                }
                return;
            }
            this.location = location;
            MyApp.bdLocation = location;
            isFirstLoc = false;
            MyLog.L(MyApp.AppName + "MyLocationListenner:" + JSON.toJSONString(location));
            LatLng currentPt = new LatLng(location.getLatitude(),
                    location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(currentPt).zoom(MyApp.zoom);
            try {
                if (mBaiduMap!=null)mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                if (mBaiduMap!=null) mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(currentPt));//将位置设为中心点
            }catch (Exception e){}
            updateMap.updateMapState(currentPt);
        }


        if (iscountinue) {
            if (location.getLongitude() == 4.9E-324 || location.getLatitude() == 4.9E-324) {
                if (MyApp.activity != null&&flag) {
                    flag=false;
                    ToastShow.showShort(MyApp.activity, "获取定位信息失败,请检查网络与GPS是否正常工作！");
                }
                return;
            }
            this.location = location;
            MyApp.bdLocation = location;
            isFirstLoc = false;
            MyLog.L(MyApp.AppName + "MyLocationListenner:" + JSON.toJSONString(location));
            LatLng currentPt = new LatLng(location.getLatitude(),
                    location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(currentPt).zoom(MyApp.zoom);
            updateMap.updateMapState(currentPt);
        }
    }

    public void close() {
        try {
            if (mLocClient != null) mLocClient.stop();//销毁
            mLocClient = null;
            inte = null;
        } catch (Exception e) {
        }
    }
}

